//
//  WKWebView+ProgressView.m
//  EClub
//
//  Created by iBenz on 16/8/4.
//  Copyright © 2016年 EC. All rights reserved.
//

#import "WKWebView+ProgressView.h"
#import "WebViewProgressView.h"
#import <objc/runtime.h>

static char kViewKey = '\0';
@implementation WKWebView (ProgressView)

+ (void)load {
    if (self==WKWebView.class) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Method oldMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
            Method newMethod = class_getInstanceMethod([self class], @selector(__Hook_dealloc));
            method_exchangeImplementations(oldMethod, newMethod);
            
            oldMethod = class_getInstanceMethod([self class], @selector(initWithFrame:configuration:));
            newMethod = class_getInstanceMethod([self class], @selector(__Hook_initWithFrame:configuration:));
            method_exchangeImplementations(oldMethod, newMethod);
        });
    }
}

- (void)__Hook_dealloc {
    [self removeObserver:self forKeyPath:@"estimatedProgress"];
    [self removeObserver:self forKeyPath:@"loading"];
    [self __Hook_dealloc];
}

- (instancetype)__Hook_initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration {
    id obj = [self __Hook_initWithFrame:frame configuration:configuration];
    if (obj) {
        CGRect frame = CGRectMake(0, -self.scrollView.contentOffset.y, self.bounds.size.width, 2.0f);
        WebViewProgressView *view = [[WebViewProgressView alloc] initWithFrame:frame];
        [self addSubview:view];
        objc_setAssociatedObject(self, &kViewKey, view, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        
        [obj addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        [obj addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
    }
    return obj;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSNumber *new = [change objectForKey:@"new"];
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat pro = new.floatValue;
        [self updateProgress:pro];
    }
    else if ([keyPath isEqualToString:@"loading"]) {
        if (!new.boolValue) {
            [self updateProgress:1.0];
        }
    }
}

- (void)updateProgress:(CGFloat)progress {
    WebViewProgressView *view = objc_getAssociatedObject(self, &kViewKey);
    [view setProgress:progress];
}

@end
